<template>
  <div class="reset-alarm-wrap list-content">
    <el-row type="flex" justify="space-between">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
        <el-form-item v-if="isMuilUnitUser&&!isSubscribe">
          <el-select filterable @change="getData(1)" v-model="formInline.orgIds" placeholder="请选择业主单位">
            <el-option
              v-for="(item,i) in orgOptions"
              :key="i"
              :label="item.shortName"
              :value="item.organizationId.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isSubscribe">
          <el-cascader
            ref="myCascader"
            v-model="formInline.relateBuildIds"
            :options="buildList"
            :props="nodeProps"
            placeholder="选择建筑物"
            clearable
            filterable
            collapse-tags
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-select
            filterable
            @change="getData(1)"
            v-model="formInline.fireTTypes"
            placeholder="请选择警情类型"
            style="width:140px;"
          >
            <el-option label="全部警情类型" value></el-option>
            <el-option label="报警" value="10"></el-option>
            <el-option label="故障" value="20"></el-option>
            <el-option label="屏蔽" value="30"></el-option>
            <el-option label="联动" value="40"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-select @change="getData(1)" v-model="formInline.resetMode">
            <el-option label="请选择复位方式" value=""></el-option>
            <el-option label="自复位" value="0"></el-option>
            <el-option label="处理后复位" value="1"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-select class="none-right-bd" @change="getData(1)" v-model="formInline.queryTimeType" style="width:120px;">
            <el-option label="复位时间" value="1"></el-option>
            <el-option label="发生时间" value="0"></el-option>
          </el-select>
          <el-date-picker
            class="none-left-bd"
            v-model="formInline.time"
            type="datetimerange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="util.intTimePickerOptions()"
            @change="getData(1)"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item>
          <el-select @change="getData(1)" v-model="formInline.isBeyondHandler">
            <el-option label="是否超时提醒" value=""></el-option>
            <el-option label="已超时" value="1"></el-option>
            <el-option label="未超时" value="0"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-select filterable v-model="formInline.handlerResultId" placeholder="全部处理类型" clearable>
            <el-option
              v-for="item in handleTypeOptions"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.trim="formInline.queryContent"
            placeholder="请输入关键词"
            @keyup.enter.native="getData(1)"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="getData(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="more-btns">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">更多操作</span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="batchDealWith">批量处理</el-dropdown-item>
            <el-dropdown-item command="export">
              导出当前数据
              <i v-if="exporting" class="el-icon el-icon-loading" style="margin-left:10px;"></i>
            </el-dropdown-item>
            <el-dropdown-item v-if="!forceAutoRefreshAlarm" divided>
              自动刷新
              <el-switch
                v-model="autoRefresh"
                active-color="#13ce66"
                @change="handleAutoRefresh"
                style="margin-left: 10px;"
              ></el-switch>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-row>
    <el-row class="overclick-wrap" :gutter="40" type="flex" justify="space-between">
      <span style="display: none">{{ freashStaticFlag }}</span>
      <el-col :span="6">
        <div
          class="item-wrap"
          @click="formInline.handlerStatus = ''"
          :class="formInline.handlerStatus == '' ? 'active' : ''"
        >
          <div class="item-content">
            <p class="item-value color-1">{{ staticObj.totalCount }}</p>
            <p class="item-title">警情总数</p>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div
          class="item-wrap"
          @click="formInline.handlerStatus = '-1'"
          :class="formInline.handlerStatus == -1 ? 'active' : ''"
        >
          <div class="item-content">
            <p class="item-value color-2">{{ staticObj.unHandlerCount }}</p>
            <p class="item-title">未处理</p>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div
          class="item-wrap"
          @click="formInline.handlerStatus = '2'"
          :class="formInline.handlerStatus == 2 ? 'active' : ''"
        >
          <div class="item-content">
            <p class="item-value color-4">{{ staticObj.processingCount }}</p>
            <p class="item-title">处理中</p>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div
          class="item-wrap"
          @click="formInline.handlerStatus = '1'"
          :class="formInline.handlerStatus == 1 ? 'active' : ''"
        >
          <div class="item-content">
            <p class="item-value color-3">{{ staticObj.handlerCount }}</p>
            <p class="item-title">已处理</p>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="tableData"
      ref="mainTable"
      style="width: 100%"
      :row-class-name="rowClassName"
      :default-sort="{prop: 'reset_time', order: 'descending'}"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" :selectable="isItPossibleSelect"></el-table-column>
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column v-if="isMuilUnitUser" prop="organizationName" label="业主单位"></el-table-column>
      <el-table-column align="center" prop="detailPic" label="图片" width="100">
        <!-- 图片的显示 -->
        <template slot-scope="scope">
          <img
            v-if="scope.row.picturesUrls||scope.row.resetPicturesUrls"
            :src="formatPicUrl(scope.row.picturesUrls||scope.row.resetPicturesUrls)"
            @click="onPreview(scope,scope.row.resetPicturesUrls?1:0)"
            style="width:80px;height:45px;"
          />
          <img
            v-else
            :src="
              scope.row.detailPic
                ? JSON.parse(scope.row.detailPic).icon || defaultImg
                : defaultImg
            "
            width="50"
            height="50"
            @click="$imgPreview"
            :data-imgpreview="
              scope.row.detailPic
                ? JSON.parse(scope.row.detailPic).icon || defaultImg
                : defaultImg
            "
          />
        </template>
      </el-table-column>
      <el-table-column prop="handlerStatus" label="处理状态" width="110">
        <template slot-scope="scope">
          <span
            :class="
              'tatus-icon-tags ' +
              util.transhandlerStatusColor(scope.row.handlerStatus)
            "
          ></span>
          {{ util.transhandlerStatusText(scope.row.handlerStatus) }}
        </template>
      </el-table-column>
      <el-table-column prop="handleTypeName" label="处理类型" width="110"></el-table-column>
      <el-table-column prop="fireTTypes" label="警情类型" width="110">
        <template slot-scope="scope">
          <div v-html="util.transFireTypeTagType(scope.row.fireTTypes)"></div>
        </template>
      </el-table-column>
      <!-- <el-table-column width="110">
        <template slot="header">
          <p>
            复位方式
            <i class="el-icon-question" style="cursor: pointer" @click="resetModeClick"></i>
          </p>
        </template>
        <template slot-scope="scope">
          <p>{{ mapResetMode(scope.row.resetMode) }}</p>
        </template>
      </el-table-column>-->
      <el-table-column prop="name" label="名称"></el-table-column>
      <!-- <el-table-column prop="" label="处理超时" width="80">
        <template slot-scope="scope">
          <span class="bg-color-1 type-tags" style="padding:0px 10px" v-if="scope.row.isBeyondHandler == 1 && scope.row.isReset == 1">超时</span>
        </template>
      </el-table-column>-->
      <el-table-column label="位置">
        <template slot-scope="scope">
          <el-link type="primary" @click="openPosition(scope.row)">{{ scope.row.fcFacilitiesAddress }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="storage_time" label="发生时间" sortable="custom" width="220">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">
            {{ scope.row.storageTime }}
            <el-link
              v-if="scope.row.createApprovePicUrl"
              class="trusted-time"
              @click="
                openTrustedTimeDialog(
                  scope.row.createApprovePicUrl,
                  scope.row.createCertificateUrl
                )
              "
            >已通过可信时间认证</el-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="持续时长">
        <template slot-scope="props" v-if="!loading">
          <div class="showTime">
            <el-progress
              :show-text="false"
              :stroke-width="20"
              :percentage="props.row.timePercent"
              :format="formatTimeStr"
            ></el-progress>
            <span>{{props.row.continueTimeStr}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="复位时间" prop="reset_time" sortable="custom" width="220">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">
            {{ scope.row.resetTime }}
            <el-link
              v-if="scope.row.restApprovePicUrl"
              class="trusted-time"
              @click="
                openTrustedTimeDialog(
                  scope.row.restApprovePicUrl,
                  scope.row.restCertificateUrl
                )
              "
            >已通过可信时间认证</el-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="附近监控">
        <template slot-scope="scope">
          <span v-if="scope.row.videoList && scope.row.videoList.length > 0">
            <el-link
              type="primary"
              v-for="(item, i) in scope.row.videoList"
              :key="i"
              @click="util.rowShowVedio(scope.row, 1, item)"
            >{{ item.name + (scope.row.videoList.length > i + 1 ? "、" : "") }}</el-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button @click="showDetail(scope.$index, scope.row)" type="text" size="small">详情</el-button>
          <span
            v-show="
              scope.row.handlerStatus !== 1 &&
              !(
                scope.row.handlerStatus === 2 &&
                scope.row.handlerAccount !== accountName
              )
            "
            class="dividing-line"
          >|</span>
          <el-button
            v-show="
              scope.row.handlerStatus !== 1 &&
              !(
                scope.row.handlerStatus === 2 &&
                scope.row.handlerAccount !== accountName
              )
            "
            @click="showDialogHandle(scope.$index, scope.row)"
            type="text"
            size="small"
          >处理</el-button>
          <span class="dividing-line">|</span>
          <el-button
            @click="
              util.openCallCenter(scope.row.organizationId, scope.row.name, 1,scope.row)
            "
            type="text"
            size="small"
          >电话呼叫</el-button>
        </template>
      </el-table-column>
      <!-- 展开详情 -->
      <el-table-column type="expand" width="1">
        <template slot-scope="scope">
          <el-tabs
            type="border-card"
            :data-row="{ scope }"
            v-model="detailList['device_' + scope.row.id].defaultTabsName"
            @tab-click="tabClick"
          >
            <span style="display: none">{{ freashFlag }}</span>
            <el-tab-pane data-label="analog" name="analog">
              <span slot="label">从发生到复位</span>
              <!-- 显示模拟量 -->
              <div v-if="scope.row.isAnalog">
                <el-card class="box-card" v-for="(item, index) in analogThresholdObj[scope.row.id]" :key="index">
                  <div class="content-analog-title">
                    <div class="titleico">{{ item.dataTypeName }}</div>
                    <div
                      class="content-analog-titleMax"
                      v-if="item.thresholdMax"
                    >报警上限：{{ item.thresholdMax }}{{ item.unit }}</div>
                    <div
                      class="content-analog-titleMax"
                      v-if="item.thresholdMin"
                    >报警下限：{{ item.thresholdMin }}{{ item.unit }}</div>
                  </div>
                  <div
                    v-show="item.unit"
                    :id="`content-analog-chart-${scope.row.id}-${item.dataTypeId}`"
                    class="content-analog-chart"
                  ></div>
                </el-card>
              </div>
              <!-- 显示非模拟量 -->
              <div v-else>
                <div :id="`content-noanalog-chart-${scope.row.id}`" class="content-analog-chart">非模拟量</div>
              </div>
            </el-tab-pane>
            <el-tab-pane data-label="pastDayRecord" name="pastDayRecord">
              <span slot="label">过去24小时状态</span>
              <status-echarts
                v-if="
                  detailList['device_' + scope.row.id].defaultTabsName ===
                    'pastDayRecord'
                "
                :info="{ id:scope.row.fcFacilitiesId,hasAnalog:scope.row.isAnalog }"
                type="1"
              ></status-echarts>
            </el-tab-pane>
            <el-tab-pane data-label="video" name="video" v-if="scope.row.picturesUrls || scope.row.resetPicturesUrls">
              <span slot="label">监控截图与回放</span>
              <img class="alarm-img" :src="formatPicUrl(scope.row.resetPicturesUrls)" @click="onPreview(scope)" />
              <img class="alarm-img" :src="formatPicUrl(scope.row.picturesUrls)" @click="onPreview(scope,1)" />
              <img
                v-for="(item,i) in scope.row.aiExtInfoList"
                :key="item.pic"
                class="alarm-img"
                :src="formatPicUrl(item.imageInfo.pic)"
                @click=" onPreview(scope,i+2) "
              />
              <div style="margin-top:5px;" v-if="scope.row.videoList&&scope.row.videoList.length>0">
                <el-button
                  type="primary"
                  icon="el-icon-video-camera"
                  @click="handleOpenDialog('ReviewVideo',scope.row)"
                >监控回放</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane data-label="record" name="record">
              <span slot="label">处理记录</span>
              <div
                v-if="
                  detailDealObj[scope.row.id] &&
                  detailDealObj[scope.row.id].length > 0
                "
              >
                <el-timeline>
                  <el-timeline-item
                    v-for="(item, i) in detailDealObj[scope.row.id]"
                    :key="i"
                    :timestamp="item.createTime"
                    placement="top"
                  >
                    <el-link
                      v-if="item.pictureUrl"
                      class="timeline-trusted-time"
                      @click="
                        openTrustedTimeDialog(
                          item.pictureUrl,
                          item.certifivateUrl
                        )
                      "
                    >已通过可信时间认证</el-link>
                    <el-card>
                      <p>
                        <b>处理状态：</b>
                        {{
                        item.status == -1
                        ? "未处理"
                        : item.status == 2
                        ? "处理中"
                        : "已处理"
                        }}
                      </p>
                      <p v-show="item.picUrl">
                        <template
                          v-for="(itemChild, index) in item.picUrl.split(',')"
                          style="display:inline-block;margin:0 2px;"
                        >
                          <img
                            v-if="'mp4,3gp,mpeg,mavip4,mov,flv'.includes(itemChild.split('.')[itemChild.split('.').length - 1].toLowerCase())"
                            :src="require('@/assets/images/video/video-detail.png')"
                            @click="$imgViewer"
                            :data-imgpreview="item.picUrl"
                            :data-imgpreviewindex="index"
                            width="100px"
                            height="100px"
                            :key="index"
                            style="margin: 0 2px"
                          />
                          <img
                            v-else
                            :key="index"
                            alt="现场处理图片"
                            :src="itemChild"
                            width="100"
                            height="100"
                            @click="$imgViewer"
                            :data-imgpreview="item.picUrl"
                            :data-imgpreviewindex="index"
                            style="margin: 0 2px"
                          />
                        </template>
                      </p>
                      <p>
                        <b>处理类型：</b>
                        {{ item.handleTypeName }}
                      </p>

                      <p v-if="item.status != 2 && item.status != -1 && item.disableElevator !== -1">
                        <b>是否禁用梯控：</b>
                        {{
                        item.disableElevator === 0
                        ? "不禁用"
                        : item.disableElevator === 1 &&
                        item.disableEndTime != "永久禁用"
                        ? "禁用，禁用周期为：" +
                        item.disableStartTime +
                        " ~ " +
                        item.disableEndTime
                        : item.disableElevator === 1 &&
                        item.disableEndTime == "永久禁用"
                        ? "禁用，禁用周期为：" + item.disableEndTime
                        : ""
                        }}
                      </p>

                      <p>
                        <b>备注：</b>
                        {{ item.remark }}
                      </p>
                      <p>
                        <b>处理人：</b>
                        {{ item.operatorName }}
                      </p>
                      <p v-if="item.isOpenPlan">
                        <b>关联预案：</b>
                        <el-link type="primary" @click="rowShowPlan(item.planId)">{{ item.planName }}</el-link>
                      </p>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
              <div v-else>暂无记录</div>
            </el-tab-pane>
            <el-tab-pane data-label="callrecord" name="callrecord">
              <span slot="label">呼叫记录</span>
              <call-record :obj="{ type: 1, id: scope.row.id }"></call-record>
            </el-tab-pane>
            <el-tab-pane data-label="base" name="base">
              <span slot="label">更多信息</span>
              <div v-if="detailMoreInfoObj[scope.row.id]">
                <p>
                  <b>警情描述：</b>
                  {{ scope.row.selfDesc }}
                </p>
                <p>
                  <b>所属消防系统：</b>
                  {{ detailMoreInfoObj[scope.row.id].systemName || "-" }}
                </p>
                <p>
                  <b>所属物联设备类别：</b>
                  {{
                  detailMoreInfoObj[scope.row.id].fcFacilitiesCategoryName ||
                  "-"
                  }}
                </p>
                <p>
                  <b>复位方式：</b>
                  {{mapResetMode(scope.row.resetMode)}}
                </p>
                <p v-if="detailMoreInfoObj[scope.row.id].assetList.length > 0">
                  <b>关联资产：</b>
                  <el-link
                    type="primary"
                    v-for="(item, i) in detailMoreInfoObj[scope.row.id]
                      .assetList"
                    :key="i"
                    @click="jumpeToAssets(item, scope.row.organizationName)"
                  >
                    {{
                    item.name +
                    (detailMoreInfoObj[scope.row.id].assetList.length > i + 1
                    ? "、"
                    : "")
                    }}
                  </el-link>
                </p>
                <p>
                  <b>实际设备上报时间：</b>
                  {{ detailMoreInfoObj[scope.row.id].createTime || "-" }}
                </p>
                <p>备注：发生时间等于入库时间，所有的时间按入库时间来</p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="sizeChange"
      @current-change="pageChange"
      :current-page="formInline.currentPageIndex"
      :page-sizes="[10, 50, 100]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="formInline.currentPageTotal"
    ></el-pagination>
    <el-dialog
      :close-on-click-modal="false"
      title="预案详情"
      width="600px"
      :visible.sync="planFormDialogHandle"
      @close="planFormDialogHandle = false"
      v-dialogDrag
    >
      <plan-detail :planForm="planForm"></plan-detail>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :title="(handleRow.length>1?'批量':'')+'警情处理'"
      width="720px"
      top="10vh"
      v-if="dialogHandle"
      :visible.sync="dialogHandle"
      @close="closeDialogHandle"
      v-dialogDrag
    >
      <deal-with-police
        :oldInfo="handleRow"
        :closeFun="closeDialogHandle"
        :formatPicUrl="formatPicUrl"
        :dealType="dealType"
      ></deal-with-police>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="可信时间认证"
      width="600px"
      v-if="trustedTimeDialog"
      :visible.sync="trustedTimeDialog"
      @close="trustedTimeDialog = false"
      v-dialogDrag
    >
      <trusted-time :info="trustedTimeInfo"></trusted-time>
    </el-dialog>
    <!-- 位置-室内地图 -->
    <multifunction-dialog v-if="dialogLocaltion" :parames="multifunctionDialogparames" @close="dialogLocaltion = false"></multifunction-dialog>
    <!-- 视频分析图片预览 -->
    <image-viewer ref="ImageViewer" :origin-list="originList"></image-viewer>
    <review-video ref="ReviewVideo" v-if="dialogVisible.ReviewVideo"></review-video>
  </div>
</template>

<script>
import {
  getAlarmInfo,
  getAlarmTotalCount,
  getRecordsHandleList,
  getAlarmFcfMoreInfo,
  getAlarmFcfAnalogInfo,
} from '@/api/alarm'
import { selectEmergencyPlanDetail } from '@/api/plan'
import { getOrgList } from '@/api/org'
import { getDictByCode } from '@/api/dic'
import util from '@/utils/util'
import MultifunctionDialog from '../MultifunctionDialog/Main'
import PlanDetail from './Dialog/PlanDetailForm'
import DealWithPolice from './Dialog/DealWithPolice'
import TrustedTime from './Dialog/TrustedTime'
import CallRecord from '../Common/CallRecord'
import ImageViewer from '@/components/TransAiPic/ImageViewer'
import StatusEcharts from '@/components/EquipmentThings/PageModel/StatusEcharts'
import { downloadExcel, objectToQueryString } from '@/utils/downloadUtil'
import ReviewVideo from './Dialog/ReviewVideo'
import { getUserBuildByAccount, getUserRelateFbsTree } from '@/api/sysConfig'
import { mapGetters, mapState } from 'vuex'

var cacheCondition = {}

export default {
  name: 'ResetAlarm',
  props: {
    parames: {
      default() {
        return false
      },
    },
  },
  components: {
    MultifunctionDialog,
    PlanDetail,
    DealWithPolice,
    TrustedTime,
    CallRecord,
    ImageViewer,
    StatusEcharts,
    ReviewVideo,
  },
  data() {
    return {
      isSubscribe: false,
      buildList: [],
      nodeProps: {
        multiple: true,
        value: 'id',
        label: 'text',
        children: 'nodes',
        emitPath: false,
      },
      dialogVisible: {
        ReviewVideo: false,
      },
      exporting: false,
      freashFlag: 0,
      freashStaticFlag: 0,
      formInline: {
        queryContent: '',
        fireTTypes: '',
        handlerStatus: '',
        // resetMode: '',
        orgIds: (this.$store.state.userinfo.isMuilUnitUser
          ? this.$store.state.userinfo.organizationIds
          : this.$store.state.userinfo.org.id
        ).toString(),
        time: '',
        currentPageSize: 10,
        currentPageIndex: 1,
        currentPageTotal: 0,
        isBeyondHandler: '',
        handlerResultId: '',
        queryTimeType: '1',
        orderByPro: 'reset_time',
        order: 'desc',
        relateBuildIds: [],
      },
      util: util,
      accountName: this.$store.state.userinfo.accountName,
      defaultImg: this.GLOBAL.defaultImg,
      tableData: [], //表格数据
      staticObj: {}, //头部各状态个数统计
      detailDealObj: {}, //展开详情中的处理详情
      detailMoreInfoObj: {}, //展开详情中的更多信息
      analogThresholdObj: {}, //模拟量阈值和标题集合
      orgOptions: [
        {
          organizationId: this.$store.state.userinfo.organizationIds,
          shortName: '全部业主单位',
        },
      ],
      loading: false,
      dialogLocaltion: false,
      multifunctionDialogparames: {},
      planFormDialogHandle: false,
      planForm: {}, //处理结果关联的预案详情
      handleRow: [], // 当前处理的行数据
      dialogHandle: false,
      selectedAlarm: [], // 多选的警情
      trustedTimeDialog: false, // 可信时间弹框
      trustedTimeInfo: {},
      searchConetent: '',
      handleTypeOptions: [],
      detailList: {},
      originList: [],
      autoRefresh: false,
      forceAutoRefreshAlarm: false,
      dealType: '1',
    }
  },
  created: function () {
    this.relateBuildIds = ''
    // 时间查询条件默认设置为上个月
    // this.formInline.time = [
    //   this.$moment(
    //     this.$moment()
    //       .subtract(30, "days")
    //       .calendar()
    //   ).format("YYYY-MM-DD HH:mm:ss"),
    //   this.$moment().format("YYYY-MM-DD HH:mm:ss")
    // ];
    this.forceAutoRefreshAlarm = FORCE_AUTO_REFRESH_ALARM
    getDictByCode({ code: 60 }).then((data) => {
      this.handleTypeOptions = data.data.dictValueObj
    })
    if (this.$route.query.getData) {
      let _this = this
      let getDataDetail = eval('(' + _this.$route.query.getData + ')')
      let getName = getDataDetail
      let arr = getName.orgIds.split(',')
      if (arr.length == 1) {
        _this.formInline.orgIds = (getName.orgIds || '').toString()
      }
      _this.formInline.time = [getName.startTime, getName.endTime]
      _this.formInline.queryContent = getName.searchConetent
      _this.searchConetent = getName.searchConetent
      _this.tableData = []
    }
    this.formInline.handlerStatus = this.$route.params.handlerStatus || ''
    // 利用大屏传递过来的数据进行筛选
    window.ejectRelevantPages = this.ejectRelevantPages
    //绑定下拉框
    if (this.isMuilUnitUser) {
      getOrgList({ queryType: 0 }).then((data) => {
        this.orgOptions.push.apply(this.orgOptions, data.data)
      })
    }
    this.getUserBuildByAccount()
  },
  activated() {
    this.exporting = this.$store.state.resetAlarmExporting
    this.autoRefresh = !!localStorage.getItem(
      `autoRefresh_alarm_${this.accountName}`
    )
    let { queryContent, dealType, data, handlerStatus } = this.$route.params
    if (handlerStatus) {
      this.formInline.handlerStatus = handlerStatus
      this.formInline.queryContent = ''
      this.getData()
    } else if (queryContent && !this.largeScreen) {
      this.formInline.queryContent = queryContent || this.searchConetent || ''
      this.getData()
    }
    this.$nextTick(() => {
      if (dealType) {
        this.showDialogHandle(0, data, dealType)
      }
    })
  },
  mounted() {
    // 对外暴露跳转方法
    window.freshResetAlarm = this.getData
  },
  methods: {
    getUserBuildByAccount() {
      getUserBuildByAccount({
        account: this.userinfo.accountName,
      })
        .then((res) => {
          if (res.data && res.data.relateBuildIds) {
            this.isSubscribe = true
            this.relateBuildIds = res.data.relateBuildIds
            this.getUserRelateFbsTree()
          }
          this.getData(1, true)
        })
        .catch(() => {
          this.getData()
        })
    },
    getUserRelateFbsTree() {
      getUserRelateFbsTree({
        orgIds: this.formInline.orgIds,
        account: this.userinfo.accountName,
      }).then((res) => {
        if (res.data) {
          this.buildList = res.data
        }
      })
    },
    handleOpenDialog(key, data) {
      this.dialogVisible[key] = true
      this.$nextTick(() => {
        this.$refs[key].init(data)
      })
    },
    rowClassName({ row }) {
      return row.handlerStatus == 1 ? 'is-handled-alarm' : ''
    },
    handleAutoRefresh() {
      localStorage.setItem(
        `autoRefresh_alarm_${this.accountName}`,
        this.autoRefresh ? '1' : ''
      )
      this.$message.success(`${this.autoRefresh ? '开启' : '关闭'}自动刷新成功`)
    },
    formatPicUrl(val) {
      if (val.indexOf('imageView2') > -1) return val
      if (
        val.indexOf('://file.kshqfire.com') < 0 &&
        val.indexOf('://file.yx-ilink.com') < 0
      )
        return val + '?w=192&h=108'
      if (val.indexOf('imageView2') < 0)
        return val + '?imageView2/2/w/192/h/108/q/75'
      return val
    },
    // 头部数据筛选
    ejectRelevantPages(item1, item2, item3) {
      let _this = this
      let getDataDetail = eval('(' + item3 + ')')
      let getName = getDataDetail
      let arr = getName.orgIds.split(',')
      if (arr.length == 1) {
        _this.formInline.orgIds = getName.orgIds
      }
      _this.formInline.time = [getName.startTime, getName.endTime]
      _this.formInline.queryContent = getName.searchConetent
      _this.searchConetent = getName.searchConetent
      _this.tableData = []
      _this.getData()
    },
    formatTimeStr(time) {
      // 框架有bug，只能这样
      let timeStr = ''
      $.each(this.tableData, (index, obj) => {
        if (obj.timePercent == time) {
          timeStr = obj.continueTimeStr
          return false
        }
      })
      return timeStr
    },
    getData(_pageIndex, force) {
      this.getList(_pageIndex, force)
      this.getStatis()
      this.pauseRefresh = false
    },
    showDetail(index, row) {
      //展开详情
      const $table = this.$refs.mainTable
      row.isExpand = !row.isExpand //给row一个自定义展开状态
      if (row && !this.detailList.hasOwnProperty('device_' + row.id)) {
        let obj = {
          defaultTabsName: 'analog',
        }
        this.$set(this.detailList, 'device_' + row.id, obj)
      }
      $table.toggleRowExpansion(row)
      if (row.isExpand) {
        this.showAlog(row)
      }
    },
    tabClick(tab, event) {
      var that = this
      var tabType = tab.$attrs['data-label']
      var row = tab.$parent.$attrs['data-row'].scope.row
      if (tabType == 'analog') {
        //模拟量
        this.showAlog(row)
      } else if (tabType == 'video') {
      } else if (tabType == 'base') {
        //更多信息
        that.loading = true
        getAlarmFcfMoreInfo({
          fcfId: row.fcFacilitiesId,
        }).then((result) => {
          that.detailMoreInfoObj[row.id] = {
            ...result.data,
            createTime: row.createTime,
          }
          that.freashFlag++
          that.loading = false
        })
      } else if (tabType == 'record') {
        //处理详情
        that.loading = true
        getRecordsHandleList({
          fireTypeId: 0,
          recordIds: row.id,
          queryType: 0,
          /* status:1 */
        }).then((result) => {
          that.detailDealObj[row.id] = result.data
          that.freashFlag++
          that.loading = false
        })
      }
    },
    showAlog(row) {
      var that = this
      if (row.isAnalog) {
        //模拟量
        //复位endTime 传复位时间
        //未复位 不传
        this.loading = true
        let param = {
          startTime: row.createTime,
          fcfId: row.fcFacilitiesId,
          num: 100,
          endTime: row.resetTime || '',
        }
        getAlarmFcfAnalogInfo(param).then((result) => {
          that.analogThresholdObj[row.id] = []
          $.each(result.data, (index, obj) => {
            that.analogThresholdObj[row.id].push({
              //server端syguo不把单位放到表层，只能遍历
              dataTypeId: obj.dataTypeId,
              dataTypeName: obj.dataTypeName,
              unit: obj.detail.length > 0 ? obj.detail[0].analogUnits : '',
              thresholdMax: obj.thresholdMax,
              thresholdMin: obj.thresholdMin,
            })
          })
          that.freashFlag++
          if (result.data) {
            setTimeout(function () {
              util.initViewsCharts(
                that.$echarts,
                result.data,
                'content-analog-chart-' + row.id,
                1
              )
            }, 500)
          }
          that.loading = false
        })
      } else {
        setTimeout(function () {
          util.initViewsCharts_noAnalog(
            that.$echarts,
            [row.storageTime, row.resetTime],
            row.fireTTypes,
            'content-noanalog-chart-' + row.id
          )
        }, 500)
      }
    },
    sizeChange(val) {
      //页码切换
      this.formInline.currentPageIndex = 1
      this.formInline.currentPageSize = val
      this.getList()
    },
    pageChange(val) {
      //翻页
      this.formInline.currentPageIndex = val
      this.getList()
      this.getStatis()
    },
    getList(_pageIndex, force) {
      if ((this.loading || this.dialogHandle) && !force) return
      //获取列表
      if (_pageIndex) {
        this.formInline.currentPageIndex = _pageIndex
      }
      let relateBuildIds = []
      if (this.isSubscribe) {
        relateBuildIds = this.$refs.myCascader.getCheckedNodes().map((n) => {
          return n.data.id
        })
      }
      this.loading = true
      let params = {
        orgIds: this.formInline.orgIds,
        pageIndex: this.formInline.currentPageIndex - 1,
        pageSize: this.formInline.currentPageSize,
        queryContent: this.formInline.queryContent.trim(),
        fireTType: this.formInline.fireTTypes,
        isBeyondHandler: this.formInline.isBeyondHandler,
        // resetMode: this.formInline.resetMode,
        handlerStatus: this.formInline.handlerStatus,
        startTime: this.formInline.time ? this.formInline.time[0] : '',
        endTime: this.formInline.time ? this.formInline.time[1] : '',
        dataType: 1, //统计类型 0:实时（未复位） 1:历史(已复位)
        handlerResultId: this.formInline.handlerResultId,
        queryTimeType: this.formInline.queryTimeType,
        orderByPro: this.formInline.orderByPro,
        order: this.formInline.order,
        relateBuildIds:
          relateBuildIds.length == 0
            ? this.relateBuildIds
            : relateBuildIds.join(','),
      }
      getAlarmInfo(params)
        .then((result) => {
          this.formInline.currentPageTotal = result.total
          if (result.data && result.data.listData) {
            $.each(result.data.listData, (index, obj) => {
              obj.timePercent = util.completionDegree(obj.continueTime, 86400)
              obj.aiExtInfoList = obj.aiExtInfo ? JSON.parse(obj.aiExtInfo) : []
            })
            this.tableData = result.data.listData
          } else {
            this.tableData = []
          }
          setTimeout(() => {
            this.loading = false
          }, 100)
          cacheCondition = params
          delete cacheCondition.pageIndex
          delete cacheCondition.pageSize
        })
        .catch(() => {
          this.loading = false
        })
    },
    getStatis() {
      if (this.dialogHandle) return
      //头部统计
      this.staticObj = {}
      this.loadingCount = true
      let relateBuildIds = []
      if (this.isSubscribe) {
        relateBuildIds = this.$refs.myCascader.getCheckedNodes().map((n) => {
          return n.data.id
        })
      }
      getAlarmTotalCount({
        orgIds: this.formInline.orgIds,
        dataType: 1, //统计类型 0:实时（未复位） 1:历史(已复位)
        queryContent: this.formInline.queryContent.trim(),
        fireTType: this.formInline.fireTTypes,
        isBeyondHandler: this.formInline.isBeyondHandler,
        handlerStatus: '' /* this.formInline.handlerStatus */,
        startTime: this.formInline.time ? this.formInline.time[0] : '',
        endTime: this.formInline.time ? this.formInline.time[1] : '',
        handlerResultId: this.formInline.handlerResultId,
        queryTimeType: this.formInline.queryTimeType,
        relateBuildIds:
          relateBuildIds.length == 0
            ? this.relateBuildIds
            : relateBuildIds.join(','),
      })
        .then((result) => {
          $.extend(this.staticObj, result.data)
          this.freashStaticFlag++
          this.loadingCount = false
        })
        .catch(() => {
          this.loadingCount = false
        })
    },
    sortChange(obj) {
      if (obj.order) {
        this.formInline.order = obj.order == 'descending' ? 'desc' : 'asc'
        this.formInline.orderByPro = obj.prop
        this.getList(1)
      }
    },
    rowShowPlan(planId) {
      this.planForm = {}
      this.planFormDialogHandle = true
      selectEmergencyPlanDetail({
        planId: planId,
      }).then((result) => {
        if (result.data) this.planForm = result.data
      })
    },
    jumpeToAssets(row, orgName) {
      let tabInfo = {
        name: 'assetList',
        title: '资产清单',
      }
      let params = {
        level: 2, // level  页面跳转显示   1-多单位   2-单单位
        orgId: row.organizationId, // 单位编码
        orgName: orgName || '', // 单位名称
        name: row.name, // 搜索内容
      }
      this.$router.push({
        name: 'assetList',
        params,
      })
    },
    // 打开显示位置弹框
    openPosition(row) {
      let that = this
      that.dialogLocaltion = true
      that.multifunctionDialogparames = {
        fcfName: row.fcFacilitiesName,
        fcfId: row.fcFacilitiesId,
      }
    },
    showDialogHandle(index, row, dealType = 1) {
      //处理
      let arr = []
      arr.push(row)
      this.dealType = dealType.toString()
      this.handleRow = arr
      this.dialogHandle = true
    },
    closeDialogHandle(refresh) {
      this.dialogHandle = false
      if (typeof refresh === 'boolean' && refresh) {
        this.getData()
      } else if (this.pauseRefresh) {
        this.getData()
      }
    },
    // 多选
    handleSelectionChange(val) {
      this.selectedAlarm = val
    },
    // 判断当前行是否可以被选择
    isItPossibleSelect(row, index) {
      // 电瓶车/煤气罐上楼不能选择
      if (
        row.handlerStatus !== 1 &&
        !(row.handlerStatus === 2 && row.handlerAccount !== this.accountName) &&
        row.fireSTypes != 113 &&
        row.fireSTypes != 115
      ) {
        return true
      } else {
        return false
      }
    },
    // 更多操作
    handleCommand(command) {
      let that = this
      switch (command) {
        case 'batchDealWith':
          that.batchDealWith()
          break
        case 'autoRefresh':
          that.handleAutoRefresh()
          break
        case 'export':
          that.handleExport()
          break
        default:
          break
      }
    },
    handleExport() {
      if (this.exporting) {
        return this.$message.warning('请稍后操作')
      }
      if (this.formInline.currentPageTotal == 0) {
        return this.$message.warning('当前列表没有数据不能导出')
      }
      var stime = this.formInline.time ? this.formInline.time[0] : ''
      var etime = this.formInline.time ? this.formInline.time[1] : ''
      if (!stime || !etime) {
        return this.$message.warning('请选择发生时间或复位时间')
      }
      this.$store.commit('setResetAlarmExporting', true)
      fetch(
        this.GLOBAL.baseURL +
          'infodata/exportFcfHistoryDatas?' +
          objectToQueryString(cacheCondition)
      )
        .then((res) => res.blob())
        .then((blob) => {
          downloadExcel(
            blob,
            '警情明细-' + new Date().toISOString().substr(0, 10) + '.xlsx'
          )
          this.$message.success('导出成功')
          this.$store.commit('setResetAlarmExporting', false)
        })
        .catch((e) => {
          this.$message.error('导出失败')
          this.$store.commit('setResetAlarmExporting', false)
        })
    },
    // 批量处理
    batchDealWith() {
      if (this.selectedAlarm.length > 0) {
        // 调用处理
        this.handleRow = this.selectedAlarm
        this.dialogHandle = true
      } else {
        this.$message.warning('请先勾选需要处理的行')
      }
    },
    // 查看复位方式说明
    resetModeClick() {
      let str = `<div>
          <p><b>复位：</b>设备从警情状态恢复到正常状态。复位方式包含自复位和处理后复位。</p>
          <br/>
          <p><b>自复位：</b>设备是否复位取决于设备现场是否复位。标准的设备都是这种。</p>
          <br/>
          <p><b>处理后复位：</b>因为硬件不提供复位信息，所以在人工对警情处理后，系统默认复位。这种情况下，系统展示设备状态可能与实际的设备状态不符，请注意。</p>
          <br/>
          <p>您可以根据设备的实际复位逻辑，通过【接警席==》系统设置==》物联设备维护】来修改复位方式。</p>
        </div>`
      this.$alert(str, '复位方式', {
        dangerouslyUseHTMLString: true,
      })
    },
    // 映射复位方式
    mapResetMode(code) {
      let mapList = {
        0: '自复位',
        1: '处理后复位',
      }
      return mapList[code] || ''
    },
    // 打开可信时间弹框
    openTrustedTimeDialog(picUrl, fileUrl) {
      if (picUrl) {
        this.trustedTimeInfo = {
          picUrl: picUrl,
          fileUrl: fileUrl,
        }
      } else {
        this.trustedTimeInfo = {}
      }
      this.trustedTimeDialog = true
    },
    onPreview(scope, index = 0) {
      let alarmPic = {
        pic: scope.row.picturesUrls,
        resultRegion: scope.row.picAlarmRegion,
      }
      let resetPic = {
        pic: scope.row.resetPicturesUrls,
        resultRegion: scope.row.picResetRegion,
      }
      let arr = []
      if (scope.row.resetPicturesUrls) {
        arr.push(resetPic)
      }
      arr.push(alarmPic)
      scope.row.aiExtInfoList.forEach((n) => {
        arr.push({
          pic: n.imageInfo.pic,
          resultRegion: JSON.stringify(n),
        })
      })
      this.srcList = arr.map((element) => {
        return element.pic
      })
      this.originList = JSON.parse(JSON.stringify(arr))
      this.$nextTick(() => {
        this.$refs.ImageViewer.switchPic(index)
      })
    },
  },
  watch: {
    handlerStatusSelect(val, oldVal) {
      if (val !== oldVal) {
        this.getList(1)
      }
    },
    // 当前在未复位警情页面，点击推送消息带条件刷新数据
    '$store.state.listQueryParam'(val) {
      if (this.dialogHandle) {
        this.pauseRefresh = true
        return
      }
      if (this.$router.currentRoute.name == 'resetAlarm') {
        this.formInline.queryContent = val.queryContent || ''
        this.getData()
        if (val.dealType) {
          this.showDialogHandle(0, val.data, val.dealType)
        }
      }
    },
    // 有警情推送，自动刷新数据
    '$store.state.resetAlarmStamp'(val) {
      if (this.dialogHandle) {
        this.pauseRefresh = true
        return
      }
      if (this.autoRefresh || this.forceAutoRefreshAlarm) {
        this.getData()
      }
    },
    '$store.state.resetAlarmExporting'(val) {
      this.exporting = val
    },
  },
  computed: {
    ...mapGetters(['isMuilUnitUser']),
    ...mapState(['userinfo']),
    handlerStatusSelect() {
      return this.formInline.handlerStatus
    },
  },
}
</script>

<style lang="scss">
.reset-alarm-wrap {
  .el-timeline-item {
    padding: 20px 0 10px;
  }
  .none-right-bd {
    .el-input__inner {
      border-right: none;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }
  }
  .none-left-bd {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
  .is-handled-alarm {
    td {
      background-color: #f5f7fa;
    }
  }
  .alarm-img {
    width: 192px;
    height: 108px;
    margin-right: 15px;
    object-fit: cover;
  }
}
</style>
